﻿using System;
using System.IO;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;

namespace Hiver.Util.Config
{
    /// <summary>
    /// Yaml帮助类
    /// </summary>
    public static class YamlHelper<T> where T : class
    {
        /// <summary>
        /// 加载Yaml配置文件
        /// </summary>
        /// <param name="url">文件路径</param>
        /// <returns></returns>
        public static T Load(string url = "application.yml")
        {
            var context = new StringReader(File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, url)));
            var deserializer = new DeserializerBuilder()
                .WithNamingConvention(CamelCaseNamingConvention.Instance)
                .Build();
            T model = deserializer.Deserialize<T>(context);
            return model;
        }

        /// <summary>
        /// 保存Yaml配置文件
        /// </summary>
        /// <param name="model">模型内容</param>
        /// <param name="url">文件路径</param>
        public static void Save(T model, string url = "application.yml")
        {
            var serializer = new SerializerBuilder().Build();
            var yaml = serializer.Serialize(model);
            File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, url), yaml);
        }
    }
}